/*
 * Designed and developed by 2017 skydoves (Jaewoong Eum)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.skydoves.colorpickerview.sliders;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.Shader;
import android.util.AttributeSet;
import androidx.annotation.ColorInt;
import androidx.appcompat.content.res.AppCompatResources;
import com.skydoves.colorpickerview.R;
import com.skydoves.colorpickerview.preference.ColorPickerPreferenceManager;

/**
 * BrightnessSlideBar extends {@link AbstractSlider} and more being specific to implement brightness
 * slide.
 */
@SuppressWarnings("unused")
public class BrightnessSlideBar extends AbstractSlider {
  
  /**
   * 设置亮度滑动条的圆角半径
   * @param cornerRadius 圆角半径值（像素）
   */
  public void setCornerRadius(float cornerRadius) {
    super.setCornerRadius(cornerRadius);
  }
  
  /**
   * 获取亮度滑动条的圆角半径
   * @return 当前圆角半径值
   */
  public float getCornerRadius() {
    return super.getCornerRadius();
  }
  
  /**
   * 设置是否启用边框
   * @param enableBorder 是否启用边框
   */
  public void setEnableBorder(boolean enableBorder) {
    super.setEnableBorder(enableBorder);
  }
  
  /**
   * 获取是否启用了边框
   * @return 是否启用边框
   */
  public boolean isEnableBorder() {
    return super.isEnableBorder();
  }
  
  /**
   * 设置是否为方形模式
   * @param squareMode 是否为方形模式
   */
  public void setSquareMode(boolean squareMode) {
    super.setSquareMode(squareMode);
    // 模式改变后需要更新渐变
    updatePaint(colorPaint);
    invalidate();
  }
  
  /**
   * 获取是否为方形模式
   * @return 是否为方形模式
   */
  public boolean isSquareMode() {
    return super.isSquareMode();
  }

  public BrightnessSlideBar(Context context) {
    super(context);
  }

  public BrightnessSlideBar(Context context, AttributeSet attrs) {
    super(context, attrs);
  }

  public BrightnessSlideBar(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
  }

  public BrightnessSlideBar(
      Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
    super(context, attrs, defStyleAttr, defStyleRes);
  }

  @Override
  protected void getAttrs(AttributeSet attrs) {
    TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.BrightnessSlideBar);
    try {
      if (a.hasValue(R.styleable.BrightnessSlideBar_selector_BrightnessSlider)) {
        int resourceId = a.getResourceId(R.styleable.BrightnessSlideBar_selector_BrightnessSlider, -1);
        if (resourceId != -1) {
          selectorDrawable = AppCompatResources.getDrawable(getContext(), resourceId);
        }
      }
      if (a.hasValue(R.styleable.BrightnessSlideBar_borderColor_BrightnessSlider)) {
        borderColor = a.getColor(R.styleable.BrightnessSlideBar_borderColor_BrightnessSlider, borderColor);
      }
      if (a.hasValue(R.styleable.BrightnessSlideBar_borderSize_BrightnessSlider)) {
        borderSize = a.getInt(R.styleable.BrightnessSlideBar_borderSize_BrightnessSlider, borderSize);
      }
      // 读取圆角半径属性
      if (a.hasValue(R.styleable.BrightnessSlideBar_cornerRadius_BrightnessSlider)) {
        cornerRadius = a.getDimension(R.styleable.BrightnessSlideBar_cornerRadius_BrightnessSlider, 0f);
      }
      // 读取是否启用边框属性
      if (a.hasValue(R.styleable.BrightnessSlideBar_enableBorder_BrightnessSlider)) {
        enableBorder = a.getBoolean(R.styleable.BrightnessSlideBar_enableBorder_BrightnessSlider, false);
      } else {
        // 默认不显示边框
        enableBorder = false;
      }
      // 读取模式属性（bar或square）
      if (a.hasValue(R.styleable.BrightnessSlideBar_mode_BrightnessSlider)) {
        int modeValue = a.getInt(R.styleable.BrightnessSlideBar_mode_BrightnessSlider, 0);
        isSquareMode = (modeValue == 1); // 1表示square模式
      }
    } finally {
      a.recycle();
    }
  }

  @Override
  protected void updatePaint(Paint colorPaint) {
    float[] hsv = new float[3];
    Color.colorToHSV(getColor(), hsv);
    
    if (isSquareMode) {
      // 方形模式：创建二维渐变，右上角最亮，左下角最暗
      hsv[2] = 0; // 暗
      int bottomLeftColor = Color.HSVToColor(hsv);
      
      hsv[2] = 1; // 亮
      int topRightColor = Color.HSVToColor(hsv);
      
      // 创建从左下角到右上角的线性渐变
      // 为了实现方形内的渐变效果，我们使用两个方向的渐变
      Shader shader = 
          new LinearGradient(
              0, getHeight(), getWidth(), 0, 
              bottomLeftColor, topRightColor, 
              Shader.TileMode.CLAMP);
      colorPaint.setShader(shader);
    } else {
      // 长条模式：水平渐变
      hsv[2] = 0;
      int startColor = Color.HSVToColor(hsv);
      hsv[2] = 1;
      int endColor = Color.HSVToColor(hsv);
      Shader shader = 
          new LinearGradient(
              0, 0, getWidth(), 0, // 只在水平方向渐变
              startColor, endColor, 
              Shader.TileMode.CLAMP);
      colorPaint.setShader(shader);
    }
  }

  @Override
  public void onInflateFinished() {
    selector.post(
        () -> {
          int defaultPosition = getWidth() - selector.getWidth();
          
          // 设置默认位置
          if (isSquareMode) {
            // 方形模式下，默认位置在右上角（最亮）
            selector.setX(defaultPosition);
            selector.setY(0);
          } else {
            // 长条模式下，默认位置在最右侧（最亮）
            selector.setX(defaultPosition);
            selector.setY((getHeight() - selector.getHeight()) / 2f);
          }

          if (getPreferenceName() != null) {
            // 从首选项恢复位置
            int savedPositionX = ColorPickerPreferenceManager.getInstance(getContext())
                    .getBrightnessSliderPosition(getPreferenceName(), defaultPosition);
            updateSelectorX(savedPositionX + getSelectorSize() / 2);
            
            // 对于方形模式，还需要恢复Y位置（如果有保存）
            if (isSquareMode) {
              // 这里可以扩展以保存和恢复Y位置
            }
          }
        });
  }

  @Override
  public @ColorInt int assembleColor() {
    float[] hsv = new float[3];
    Color.colorToHSV(getColor(), hsv);
    
    if (isSquareMode) {
      // 方形模式：结合X和Y位置计算亮度
      // 这里可以使用更复杂的算法，简单起见我们使用平均
      hsv[2] = (selectorPosition + selectorPositionY) / 2f;
    } else {
      // 长条模式：仅使用X位置
      hsv[2] = selectorPosition;
    }
    
    if (colorPickerView != null && colorPickerView.getAlphaSlideBar() != null) {
      int alpha = (int) (colorPickerView.getAlphaSlideBar().getSelectorPosition() * 255);
      return Color.HSVToColor(alpha, hsv);
    }
    return Color.HSVToColor(hsv);
  }
}
